package cn.yunhe.proxy.dynamic.interceptor;

import java.lang.reflect.Method;
import cn.yunhe.proxy.dynamic.dao.Transaction;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * CGLIB的动态代理,
 * 代理对象是目标对象的子类, 
 * 拦截器必须实现MethodInterceptor接口
 * 
 * @author ZSL
 *
 */
public class MyInterceptor implements MethodInterceptor {
	private Object target;
	private Transaction transaction;

	public MyInterceptor(Object target, Transaction transaction) {
		super();
		this.target = target;
		this.transaction = transaction;
	}

	/**
	 * 产生代理对象
	 */
	public Object createProxy() {
		Enhancer enhancer = new Enhancer();
		enhancer.setCallback(this);// 回调函数 拦截器
		enhancer.setSuperclass(this.target.getClass());// 设置代理对象的父类
		return enhancer.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if (method.getName().equals("updatePerson") || method.getName().equals("savePerson")
				|| method.getName().endsWith("deletePerson")) {
			transaction.beginTransaction();
			Object result = proxy.invokeSuper(obj, args);// 目标对象的目标方法
			//Object result = method.invoke(target, args);// 目标对象的目标方法
			transaction.commit();
			return result;
		} else {
			return proxy.invokeSuper(obj, args);// 目标对象的目标方法
			//return method.invoke(target, args);// 目标对象的目标方法
		}

	}

}
